package com.jzo2o.foundations.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.expcetions.DBException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.domain.Serve;
import com.jzo2o.foundations.model.domain.ServeItem;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.IRegionService;
import com.jzo2o.foundations.service.IServeItemService;
import com.jzo2o.foundations.service.IServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 区域服务接口实现类
 *
 * @Author wd
 * @Date 2025/6/30 17:34
 */
@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {
    /**
     * 查询区域服务分页列表
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult<ServeResDTO> pageList(ServePageQueryReqDTO dto) {
//        PageHelper.startPage(dto.getPageNo().intValue(),dto.getPageSize().intValue());
//        Page<ServeResDTO> page = (Page<ServeResDTO>) this.getBaseMapper().queryList(dto.getRegionId());
//        PageResult pageResult = new PageResult();
//        double ceil = Math.ceil(page.getTotal() / (double) page.getPageSize());
//        pageResult.setPages((long)ceil);
//        pageResult.setTotal(page.getTotal());
//        pageResult.setList(page.getResult());
//        return pageResult;
        return PageHelperUtils.selectPage(dto, () -> this.getBaseMapper().queryList(dto.getRegionId()));
    }

    @Autowired
    private IRegionService regionService;

    @Autowired
    private IServeItemService serveItemService;
    /**
     * 批量新增区域服务
     *
     * @param dtoList
     */
    @Transactional
    @Override
    public void batchAdd(List<ServeUpsertReqDTO> dtoList) {
        List<Serve> serveList = new ArrayList<>();

        dtoList.forEach(x->{
            //1. 判断是否已选择区域
            if(x.getRegionId()==null) {
                throw new BadRequestException("未选择区域");
            }

            //2. 判断区域是否存在
            Region region = regionService.getById(x.getRegionId());
            if(region==null) {
                throw new BadRequestException("区域不存在");
            }

            //3. 判断服务项是否存在
            ServeItem item = serveItemService.getById(x.getServeItemId());
            if(item==null) {
                throw new BadRequestException("服务项不存在");
            }

            //4. 判断服务项是否已启用
            if(item.getActiveStatus() != FoundationStatusEnum.ENABLE.getStatus()) {
                throw new BadRequestException("服务项未启用");
            }

            //5. 判断服务项是否已经添加过
            Integer count = this.lambdaQuery().eq(Serve::getRegionId, x.getRegionId())
                    .eq(Serve::getServeItemId, x.getServeItemId())
                    .count();
            if(count>0) {
                throw new BadRequestException("服务项已添加过");
            }

            //6. 封装服务数据新增表中
            Serve serve = BeanUtil.toBean(x, Serve.class);
            serve.setCityCode(region.getCityCode());//城市编码
            serveList.add(serve);
        });

        if(CollUtil.isNotEmpty(serveList)) {
            boolean result = this.saveBatch(serveList);
            if(!result) {
                throw new DBException("新增区域服务失败");
            }
        }
    }

    /**
     * 修改服务价格
     *
     * @param id
     * @param price
     */
    @Override
    public void updatePrice(Long id, BigDecimal price) {
//1.判断服务是否存在
        Serve serve = this.getById(id);
        if(serve==null) {
            throw new BadRequestException("服务不存在");
        }

        //2.判断服务是否已上架
        if(serve.getSaleStatus()==FoundationStatusEnum.ENABLE.getStatus()) {
            throw new BadRequestException("服务上架中，无法修改");
        }

        //3. 更新价格
        boolean result = this.lambdaUpdate().eq(Serve::getId, id)
                .set(Serve::getPrice, price)
                .update();
        if(!result) {
            throw new DBException("更新价格失败");
        }
    }

    /**
     * 服务上下架
     *
     * @param id
     */
    @Transactional
    @Override
    public void onSale(Long id) {
        //1. 判断服务是否存在
        Serve serve = this.getById(id);
        if(serve==null) {
            throw new BadRequestException("服务不存在");
        }

        //2. 判断区域是否存在
        Integer regionCount = regionService.lambdaQuery().eq(Region::getId, serve.getRegionId()).count();
        if(regionCount==0) {
            throw new BadRequestException("区域不存在");
        }

        //3. 判断服务状态是否已上架
        if(serve.getSaleStatus()==FoundationStatusEnum.ENABLE.getStatus()) {
            throw new BadRequestException("服务已上架");
        }

        //4. 判断服务项是否存在
        ServeItem item = serveItemService.getById(serve.getServeItemId());
        if(item==null) {
            throw new BadRequestException("服务项不存在");
        }

        //5. 判断服务项是否已启用
        if(item.getActiveStatus()!=FoundationStatusEnum.ENABLE.getStatus()) {
            throw new BadRequestException("服务项未启用");
        }

        //6. 修改服务为已上架
        boolean result = this.lambdaUpdate().eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
                .update();
        if(!result) {
            throw new DBException("更新服务上架失败");
        }
    }


}
